package org.budo.sms.service.aliyun;

import java.util.Map;

import org.budo.sms.service.api.BudoSmsService;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author limingwei
 *         https://help.aliyun.com/document_detail/66496.html?spm=a2c1g.8271268.10000.90.3755df250n6Gg2
 *         https://api.aliyun.com/new#/?product=Dysmsapi&api=SendSms&params=%7B%22RegionId%22%3A%22cn-hangzhou%22%2C%22PhoneNumbers%22%3A%22%22%2C%22SignName%22%3A%22%22%2C%22TemplateCode%22%3A%22%22%7D&tab=DEMO&lang=JAVA
 */
@Slf4j
@Getter
@Setter
public class BudoAliyunSmsService implements BudoSmsService {
    private String regionId = "cn-hangzhou";

    private String signName;

    private String accessKey;

    private String accessSecret;

    @Override
    public String sendSms(String to, String template, Map<String, Object> parameters) {
        DefaultProfile profile = DefaultProfile.getProfile(this.getRegionId(), this.getAccessKey(), this.getAccessSecret());
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        request.putQueryParameter("RegionId", this.getRegionId());
        request.putQueryParameter("SignName", this.getSignName());

        request.putQueryParameter("PhoneNumbers", to);
        request.putQueryParameter("TemplateCode", template);

        request.putQueryParameter("TemplateParam", JSON.toJSONString(parameters));

        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info("#46 after send, response.data=" + response.getData());
            return response.getData();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}